package com.topcheer.provider.common.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.topcheer.common.base.CommonConstants;
import com.topcheer.common.datasource.EnableDynamicDateSource;
import com.topcheer.common.datasource.dynamic.DataSourceBuilder;
import com.topcheer.common.datasource.dynamic.DynamicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xutao
 * @Package com.example.baseline.common.config
 * @Description: ${todo}
 * @date 2020/4/3 16:33
 */
@Configuration
@ConditionalOnBean(annotation =EnableDynamicDateSource.class )
@MapperScan("com.example.baseline.*.mapper")
public class DataSourceAutoConfiguration  {

    @Bean
    @ConfigurationProperties("spring.datasource")
    public DataSource firstDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    DynamicDataSource dynamicDataSource(){
        DataSource dataSource = firstDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(CommonConstants.PRIMARY,dataSource);
        return new DynamicDataSource(dataSource,targetDataSources);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource());
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapping/**/*.xml"));
//        sqlSessionFactoryBean.setTypeAliasesPackage("com.wch.financial.domain");
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 注册 sqlSessionTemplate
     *
     * @param sqlSessionFactory
     * @return
     */
    @Bean
    public SqlSessionTemplate financialMasterSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dynamicDataSource());
    }

    @Bean
    DataSourceBuilder dataSourceBuilder(){
        return new DruidDataSourceImpl();
    }
}
